package store

import (
	mystore "HelloWorld/store"
	"HelloWorld/store/factory"
	"sync"
)

func init() {
	factory.Register("mem", &MemStore{books: make(map[string]mystore.Book)})
}

type MemStore struct {
	sync.Mutex
	books map[string]mystore.Book
}

func (ms *MemStore) Create(book *mystore.Book) error {
	ms.Lock()
	defer ms.Unlock()

	if _, ok := ms.books[book.ID]; ok {
		return mystore.ErrBookExisted
	}
	ms.books[book.ID] = *book
	return nil
}

func (ms *MemStore) Get(id string) (*mystore.Book, error) {
	ms.Lock()
	defer ms.Unlock()

	book, ok := ms.books[id]
	if !ok {
		return nil, mystore.ErrBookNotFound
	}
	return &book, nil
}
func (ms *MemStore) Update(book *mystore.Book) error {
	ms.Lock()
	defer ms.Unlock()

	if _, ok := ms.books[book.ID]; !ok {
		return mystore.ErrBookNotFound
	}
	ms.books[book.ID] = *book
	return nil
}

func (ms *MemStore) Delete(id string) error {
	ms.Lock()
	defer ms.Unlock()

	if _, ok := ms.books[id]; !ok {
		return mystore.ErrBookNotFound
	}
	delete(ms.books, id)
	return nil
}

func (ms *MemStore) GetAll() ([]*mystore.Book, error) {
	ms.Lock()
	defer ms.Unlock()

	var books []*mystore.Book
	for _, book := range ms.books {
		books = append(books, &book)
	}
	return books, nil
}
